<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 4.2.1">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"yoursite.com","root":"/","scheme":"Pisces","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":false,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}}};
  </script>

  <meta name="description" content="1 项目概述1.1项目介绍&amp;ensp;&amp;ensp;&amp;ensp;&amp;ensp;基于SpringBoot+Mybatis框架和MySql数据库做了一个资源分享网站。该网站可以用于资源分享，也可以充当百度云盘重要资料整理说明的文档。其主要功能按照权限进行划分可分成游客、用户和管理员三大部分，游客：游客可进行注册，阅览资源；用户：注册用户可进行登录，密码找回，对自己的资源进行管理（分享资源或充值可获得积分）">
<meta property="og:type" content="article">
<meta property="og:title" content="资源分享网项目笔记">
<meta property="og:url" content="http://yoursite.com/2020/06/28/pro/index.html">
<meta property="og:site_name" content="丛同学已经准备就绪">
<meta property="og:description" content="1 项目概述1.1项目介绍&amp;ensp;&amp;ensp;&amp;ensp;&amp;ensp;基于SpringBoot+Mybatis框架和MySql数据库做了一个资源分享网站。该网站可以用于资源分享，也可以充当百度云盘重要资料整理说明的文档。其主要功能按照权限进行划分可分成游客、用户和管理员三大部分，游客：游客可进行注册，阅览资源；用户：注册用户可进行登录，密码找回，对自己的资源进行管理（分享资源或充值可获得积分）">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20200605175857177.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQ1NzcwNTMy,size_16,color_FFFFFF,t_70">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20200605111012339.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQ1NzcwNTMy,size_16,color_FFFFFF,t_70">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20200605163940258.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQ1NzcwNTMy,size_16,color_FFFFFF,t_70">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20200607085637641.png">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20200605210256807.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQ1NzcwNTMy,size_16,color_FFFFFF,t_70">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20200606091233150.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQ1NzcwNTMy,size_16,color_FFFFFF,t_70">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20200606151432958.png">
<meta property="og:image" content="https://img-blog.csdnimg.cn/2020060709182763.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQ1NzcwNTMy,size_16,color_FFFFFF,t_70">
<meta property="article:published_time" content="2020-06-28T15:10:10.000Z">
<meta property="article:modified_time" content="2020-07-09T15:12:06.504Z">
<meta property="article:author" content="丛同学">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://img-blog.csdnimg.cn/20200605175857177.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQ1NzcwNTMy,size_16,color_FFFFFF,t_70">

<link rel="canonical" href="http://yoursite.com/2020/06/28/pro/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>资源分享网项目笔记 | 丛同学已经准备就绪</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">丛同学已经准备就绪</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">http://chieflion.gitee.io/</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a>

  </li>
  </ul>
</nav>




</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2020/06/28/pro/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="丛同学">
      <meta itemprop="description" content="热爱可抵岁月满长">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="丛同学已经准备就绪">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          资源分享网项目笔记
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2020-06-28 23:10:10" itemprop="dateCreated datePublished" datetime="2020-06-28T23:10:10+08:00">2020-06-28</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2020-07-09 23:12:06" itemprop="dateModified" datetime="2020-07-09T23:12:06+08:00">2020-07-09</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/%E9%A1%B9%E7%9B%AE/" itemprop="url" rel="index"><span itemprop="name">项目</span></a>
                </span>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h2 id="1-项目概述"><a href="#1-项目概述" class="headerlink" title="1 项目概述"></a>1 项目概述</h2><p><strong>1.1项目介绍</strong><br>&ensp;&ensp;&ensp;&ensp;基于SpringBoot+Mybatis框架和MySql数据库做了一个资源分享网站。该网站可以用于资源分享，也可以充当百度云盘重要资料整理说明的文档。其主要功能按照权限进行划分可分成游客、用户和管理员三大部分，<strong>游客</strong>：游客可进行注册，阅览资源；<strong>用户</strong>：注册用户可进行登录，密码找回，对自己的资源进行管理（分享资源或充值可获得积分）对他人的资源下载（下载需要消耗积分），对下载的资源进行评价评价、发布资源获取积分积分等；<strong>管理员</strong>：管理员可对资源类型进行管理、对资源和评价进行审核、并可以完成对登录人数、各类别资源发布数目等信息进行统计的任务。为减少用户对数据库的操作以提高系统效率，本项目采用了Redis数据库充当缓存，并用Shiro框架实现认证和权限管理。</p>
<a id="more"></a>
<p><strong>1.2技术选型</strong><br>&ensp;&ensp;&ensp;&ensp;SpringBoot作为主体框架；MyBatis作为持久层框架；数据库选用MySql；并用Redis实现了对热门数据和常用数据的缓存（是不是也可以进行阅读量的增加）以减少对MySql的操作提高效率；Javamail实现：密码找回；Shiro作为Java安全框架,执行身份验证与授权。具体功能及核心实现如下所示。<br><strong>1.3 项目流程</strong><br>&ensp;&ensp;&ensp;&ensp;1 建立数据库和数据表；<br>&ensp;&ensp;&ensp;&ensp;2 利用IDEA创建SpringBoot项目；<br>&ensp;&ensp;&ensp;&ensp;3 对Maven工程的Pom.xml进行配置，以导入依赖；<br>&ensp;&ensp;&ensp;&ensp;4 在application.yml对Datasource等信息进行配置;<br>&ensp;&ensp;&ensp;&ensp;5 引入前端资源文件；<br>&ensp;&ensp;&ensp;&ensp;6 根据业务需求编写实体类Entity代码和Mapper层代码、Mapper.xml、service层接口和实现类、controller层的接口和实现类；<br>&ensp;&ensp;&ensp;&ensp;7测试并部署（这一步实际没进行）；</p>
<h2 id="2-数据库建立"><a href="#2-数据库建立" class="headerlink" title="2 数据库建立"></a>2 数据库建立</h2><p><strong>2.1数据库中的表以及表间关系</strong><br>&ensp;&ensp;&ensp;&ensp;创建数据库，并建立用户表、资源表、资源类型表、消息表、评价表、资源下载表和友情链接表，各个表之间的关系如图1所示。</p>
<div align=center>

<p><img src="https://img-blog.csdnimg.cn/20200605175857177.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQ1NzcwNTMy,size_16,color_FFFFFF,t_70" alt="在这里插入图片描述"></div><br><strong>2.2所用mysql知识点总结</strong><br>&ensp;&ensp;&ensp;&ensp;1 建立表的过程中，各个表要满足三大范式；<br>&ensp;&ensp;&ensp;&ensp;2 存储引擎选择上，必须是InnoDB存储引擎，而不能是MyISAM存储引擎，因为MyISAM存储引擎是不支持外键的；<br>&ensp;&ensp;&ensp;&ensp;3 涉及多表查询；<br>&ensp;&ensp;&ensp;&ensp;4 外键约束的对业务逻辑来讲，也很重要；Mysql包含四种外键约束：<br>&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;CASCADE：父表delete、update的时候，子表会delete、update掉关联记录；<br>&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;SET NULL：父表delete、update的时候，子表会将关联记录的外键字段所在列设为null，所以注意在设计子表时外键不能设为not null；<br>&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;RESTRICT：如果想要删除父表的记录时，而在子表中有关联该父表的记录，则不允许删除父表中的记录；<br>&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;NO ACTION：同 RESTRICT，也是首先先检查外键；</p>
<h2 id="3-后端核心功能及代码实现"><a href="#3-后端核心功能及代码实现" class="headerlink" title="3 后端核心功能及代码实现"></a>3 后端核心功能及代码实现</h2><p>&ensp;&ensp;&ensp;&ensp;在此部分进行之前要先解决掉项目热更新热部署的问题，来减少启动，同时加入filter过滤规则，对所有页面进行过滤（注意要把filter声明为配置类）。<br> <strong>3.1 用户主页相关功能</strong><br><strong>3.1.1  注册功能</strong><br>&ensp;&ensp;&ensp;&ensp;用户通过添加用户名、密码、昵称、邮箱和性别几个属性进行注册，同时具备通过QQ进行注册的功能。（QQ注册的功能后面完善）。在进行存储注册之前，要先写好user Entity，再写Mapper层同时注入Sql，再写service层并进行事务和权限验证方面的操作，最后再对controller进行定义。<br>在这个功能中用到的UserService方法主要包含如下几种：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"> <span class="comment">// 根据用户名查找用户实体</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> User <span class="title">findByUserName</span><span class="params">(String userName)</span></span>;</span><br><span class="line"> <span class="comment">//根据邮箱查找用户实体</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> User <span class="title">findByEmail</span><span class="params">(String email)</span></span>;</span><br><span class="line"> <span class="comment">// 添加或修改用户信息</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">save</span><span class="params">(User user)</span></span>;</span><br><span class="line"> * 根据id获取用户信息</span><br><span class="line"><span class="function"><span class="keyword">public</span> User <span class="title">getById</span><span class="params">(Integer id)</span></span>;</span><br></pre></td></tr></table></figure>

<p>UserController中的关于注册的方法如下，其中BindingResult提供了参数校验功能。在<strong>项目当中少不了入参校验，服务器和浏览器互不信任，不能因为前端加入参判断了后台就不处理了，这样是不对的</strong>。比如前台传过来一个对象作为入参参数，这个对象中有些属性允许为空，有些属性不允许为空，那么我们可以使用@Valid+BindingResult进行controller参数校验。同时用户注册的过程中为了信息安全，不应将明文密码存入数据库，要进行MD5加密处理。controller如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment">  * 用户注册</span></span><br><span class="line"><span class="comment">  */</span></span><br><span class="line"> <span class="meta">@ResponseBody</span></span><br><span class="line"> <span class="meta">@PostMapping</span>(<span class="string">"/register"</span>)</span><br><span class="line"> <span class="function"><span class="keyword">public</span> Map&lt;String,Object&gt; <span class="title">register</span><span class="params">(@Valid User user, BindingResult bindingResult)</span></span>&#123;</span><br><span class="line">     Map&lt;String,Object&gt; map = <span class="keyword">new</span> HashMap&lt;&gt;();</span><br><span class="line">     <span class="keyword">if</span>(bindingResult.hasErrors())&#123;</span><br><span class="line">         map.put(<span class="string">"success"</span>,<span class="keyword">false</span>);</span><br><span class="line">         map.put(<span class="string">"errorInfo"</span>,bindingResult.getFieldError().getDefaultMessage());</span><br><span class="line">     &#125;<span class="keyword">else</span> <span class="keyword">if</span>(userService.findByUserName(user.getUserName())!=<span class="keyword">null</span>)&#123;</span><br><span class="line">         map.put(<span class="string">"success"</span>,<span class="keyword">false</span>);</span><br><span class="line">         map.put(<span class="string">"errorInfo"</span>,<span class="string">"用户名已存在，请更换！"</span>);</span><br><span class="line">     &#125;<span class="keyword">else</span> <span class="keyword">if</span>(userService.findByEmail(user.getEmail())!=<span class="keyword">null</span>)&#123;</span><br><span class="line">         map.put(<span class="string">"success"</span>,<span class="keyword">false</span>);</span><br><span class="line">         map.put(<span class="string">"errorInfo"</span>,<span class="string">"邮箱已存在，请更换！"</span>);</span><br><span class="line">     &#125;<span class="keyword">else</span>&#123;</span><br><span class="line">         <span class="comment">//CryptographyUtil.md5()是自定义的用于MD5加密的方法</span></span><br><span class="line">         user.setPassword(CryptographyUtil.md5(user.getPassword(),CryptographyUtil.SALT));</span><br><span class="line">         user.setRegistrationDate(<span class="keyword">new</span> Date());</span><br><span class="line">         user.setLatelyLoginTime(<span class="keyword">new</span> Date());</span><br><span class="line">         user.setHeadPortrait(<span class="string">"tou.jpg"</span>);</span><br><span class="line">         userService.save(user);</span><br><span class="line">         map.put(<span class="string">"success"</span>,<span class="keyword">true</span>);</span><br><span class="line">     &#125;</span><br><span class="line">     <span class="keyword">return</span> map;</span><br><span class="line"> &#125;</span><br></pre></td></tr></table></figure>
<p><strong>3.1.2 登录功能–Shrio认证</strong><br>&ensp;&ensp;&ensp;&ensp;本项目在认证和权限的实现上采用<strong>Shrio</strong>，Shiro是Apache下的一个开源项目。shiro主要有三大功能模块： Subject：主体，一般指用户，对应用提供的API的核心；SecurityManager：安全管理器，管理所有Subject，可以配合内部安全组件。(类似于SpringMVC中的DispatcherServlet)；Realms：用于进行权限信息的验证，一般需要自己实现。相当于DataSource。在进行认证和权限管理之前，我们应该先定义好Shrio的配置类，并自定义Realms。<br>自定义Realm中要实现权限管理的方法和认证的方法，截止到目前只涉及认证方法，代码很固定，如下所示：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"> <span class="comment">// 权限认证</span></span><br><span class="line"> <span class="comment">//Token中包含了前端传来的userName+passWord</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> AuthenticationInfo <span class="title">doGetAuthenticationInfo</span><span class="params">(AuthenticationToken authenticationToken)</span> <span class="keyword">throws</span> AuthenticationException </span>&#123;</span><br><span class="line">    String userName = (String) authenticationToken.getPrincipal();</span><br><span class="line">    User user = userService.findByUserName(userName);</span><br><span class="line">    <span class="keyword">if</span>(user==<span class="keyword">null</span>)&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">    &#125;<span class="keyword">else</span>&#123;</span><br><span class="line">        AuthenticationInfo authenticationInfo = <span class="keyword">new</span> SimpleAuthenticationInfo(user.getUserName(),user.getPassword(),<span class="string">"xx"</span>);</span><br><span class="line">        <span class="keyword">return</span> authenticationInfo;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>&ensp;&ensp;&ensp;&ensp;Realm自定义完成后，需要定义Shrio的配置类，配置类中包含了三个核心方法，从上到下依次为：public ShiroFilterFactoryBean shirFilter(SecurityManager securityManager) 在这个方法中定义拦截器，过滤链；public SecurityManager securityManager()  用于返回SecurityManager；public MyRealm myRealm() 在这个方法中返回上文自定义的Realm。<strong>过滤链定义，从上往下执行，一般将</strong>/<strong>**放在最下面</strong>     这是个坑，一不小心代码就不好使了，authc：所有的url必须认证通过才可以访问     anon:所有url都可以匿名访问 ，配置不会被拦截的链接。（filters:管理全部过滤器，包括默认的关于身份验证和权限验证的过滤器，这些过滤器分为两组，一组是认证过滤器，有anon，authcBasic，auchc，user，一组是授权过滤器，有perms，roles，ssl，rest，port；）所以在定义拦截链的过程中，根目录、静态页面、静态资源、登录页面、登录方法、注册方法等都不需要进行过滤；除了不需要进行过滤的页面和方法以外，其他的直接定义为 filterChainDefinitionMap.put(“/星星”,”authc”)即可。代码如下所示（截止到目前还没涉及太多权限问题，这里的代码是项目整体的Shrio核心代码）：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br></pre></td><td class="code"><pre><span class="line">Bean</span><br><span class="line">    <span class="function"><span class="keyword">public</span> ShiroFilterFactoryBean <span class="title">shirFilter</span><span class="params">(SecurityManager securityManager)</span></span>&#123;</span><br><span class="line">        ShiroFilterFactoryBean shiroFilterFactoryBean = <span class="keyword">new</span> ShiroFilterFactoryBean();</span><br><span class="line">        <span class="comment">//必须设置securityManager</span></span><br><span class="line">        shiroFilterFactoryBean.setSecurityManager(securityManager);</span><br><span class="line">        <span class="comment">//如果不设置，默认会自动寻找Web工程根目录下的"login.jsp"页面</span></span><br><span class="line">        shiroFilterFactoryBean.setLoginUrl(<span class="string">"/"</span>);</span><br><span class="line">        Map&lt;String,String&gt; filterChainDefinitionMap = <span class="keyword">new</span> LinkedHashMap&lt;&gt;();</span><br><span class="line">        filterChainDefinitionMap.put(<span class="string">"/"</span>,<span class="string">"anon"</span>);</span><br><span class="line">        filterChainDefinitionMap.put(<span class="string">"/static/**"</span>,<span class="string">"anon"</span>);</span><br><span class="line">        filterChainDefinitionMap.put(<span class="string">"/ueditor/**"</span>,<span class="string">"anon"</span>);</span><br><span class="line">        filterChainDefinitionMap.put(<span class="string">"/upload/**"</span>,<span class="string">"anon"</span>);</span><br><span class="line">        filterChainDefinitionMap.put(<span class="string">"/user/register.html"</span>,<span class="string">"anon"</span>);</span><br><span class="line">        filterChainDefinitionMap.put(<span class="string">"/user/login.html"</span>,<span class="string">"anon"</span>);</span><br><span class="line">        filterChainDefinitionMap.put(<span class="string">"/user/findPassword.html"</span>,<span class="string">"anon"</span>);</span><br><span class="line">        filterChainDefinitionMap.put(<span class="string">"/user/register"</span>,<span class="string">"anon"</span>);</span><br><span class="line">        filterChainDefinitionMap.put(<span class="string">"/user/login"</span>,<span class="string">"anon"</span>);</span><br><span class="line">        filterChainDefinitionMap.put(<span class="string">"/user/sendEmail"</span>,<span class="string">"anon"</span>);</span><br><span class="line">        filterChainDefinitionMap.put(<span class="string">"/user/checkYzm"</span>,<span class="string">"anon"</span>);</span><br><span class="line">        filterChainDefinitionMap.put(<span class="string">"/user/bindEmail"</span>,<span class="string">"anon"</span>);</span><br><span class="line">        filterChainDefinitionMap.put(<span class="string">"/QQ/qqLogin"</span>,<span class="string">"anon"</span>);</span><br><span class="line">        filterChainDefinitionMap.put(<span class="string">"/article/**"</span>,<span class="string">"anon"</span>);</span><br><span class="line">        filterChainDefinitionMap.put(<span class="string">"/comment/**"</span>,<span class="string">"anon"</span>);</span><br><span class="line">        filterChainDefinitionMap.put(<span class="string">"/connect"</span>,<span class="string">"anon"</span>);</span><br><span class="line">        filterChainDefinitionMap.put(<span class="string">"/buyVIP"</span>,<span class="string">"anon"</span>);</span><br><span class="line">        filterChainDefinitionMap.put(<span class="string">"/fbzyzjf"</span>,<span class="string">"anon"</span>);</span><br><span class="line">        filterChainDefinitionMap.put(<span class="string">"/admin/login.html"</span>,<span class="string">"anon"</span>);</span><br><span class="line">        filterChainDefinitionMap.put(<span class="string">"/user/bindEmail.html"</span>,<span class="string">"anon"</span>);</span><br><span class="line">        filterChainDefinitionMap.put(<span class="string">"/user/logout"</span>,<span class="string">"logout"</span>);</span><br><span class="line">        filterChainDefinitionMap.put(<span class="string">"/**"</span>,<span class="string">"authc"</span>);</span><br><span class="line">        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);</span><br><span class="line">        <span class="keyword">return</span> shiroFilterFactoryBean;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> SecurityManager <span class="title">securityManager</span><span class="params">()</span></span>&#123;</span><br><span class="line">        DefaultWebSecurityManager securityManager = <span class="keyword">new</span> DefaultWebSecurityManager();</span><br><span class="line">        <span class="comment">//设置realm</span></span><br><span class="line">        securityManager.setRealm(myRealm());</span><br><span class="line">        <span class="keyword">return</span> securityManager;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 身份认证realm</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> MyRealm <span class="title">myRealm</span><span class="params">()</span></span>&#123;</span><br><span class="line">        MyRealm myRealm = <span class="keyword">new</span> MyRealm();</span><br><span class="line">        <span class="keyword">return</span> myRealm;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
<p>&ensp;&ensp;&ensp;&ensp;在定义好Shrio配置类后，就要写登录的controller代码了，因为登录成功后一般会将用户信息添加到Session中，所以controller方法接受的参数中应该包含session。具体实现描述：当用户名和密码都不为空的时候，就要进行是否可以登录的判断了，这个判断是交给shrio来完成的，首先获取subject对象，然后将用户名和密码作为参数建立Token对象，再调用subject的login等，最后登录成功后将用户信息添加到session中，具体代码如下所示（其实整个登录过程完全可以由Realm来完成，具体实现并不唯一）：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 用户登录</span></span><br><span class="line"><span class="comment"> * StringUtil.isEmpty（）是个自定义的判断字符串是否为空的工具类，其实没太大实际意义；</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@ResponseBody</span></span><br><span class="line"><span class="meta">@PostMapping</span>(<span class="string">"/login"</span>)</span><br><span class="line"><span class="function"><span class="keyword">public</span> Map&lt;String,Object&gt; <span class="title">login</span><span class="params">(User user, HttpSession session)</span></span>&#123;</span><br><span class="line">    Map&lt;String,Object&gt; map = <span class="keyword">new</span> HashMap&lt;&gt;();</span><br><span class="line">    <span class="keyword">if</span>(StringUtil.isEmpty(user.getUserName()))&#123;</span><br><span class="line">        map.put(<span class="string">"success"</span>,<span class="keyword">false</span>);</span><br><span class="line">        map.put(<span class="string">"errorInfo"</span>,<span class="string">"请输入用户名！"</span>);</span><br><span class="line">    &#125;<span class="keyword">else</span> <span class="keyword">if</span>(StringUtil.isEmpty(user.getPassword()))&#123;</span><br><span class="line">        map.put(<span class="string">"success"</span>,<span class="keyword">false</span>);</span><br><span class="line">        map.put(<span class="string">"errorInfo"</span>,<span class="string">"请输入密码！"</span>);</span><br><span class="line">    &#125;<span class="keyword">else</span>&#123;</span><br><span class="line">        Subject subject = SecurityUtils.getSubject();</span><br><span class="line">        UsernamePasswordToken token = <span class="keyword">new</span> UsernamePasswordToken(user.getUserName(),CryptographyUtil.md5(user.getPassword(),CryptographyUtil.SALT));</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            subject.login(token);       <span class="comment">//登录验证</span></span><br><span class="line">            String userName = (String) SecurityUtils.getSubject().getPrincipal();</span><br><span class="line">            User currentUser = userService.findByUserName(userName);</span><br><span class="line">            <span class="keyword">if</span> (currentUser.isOff()) &#123;</span><br><span class="line">                map.put(<span class="string">"success"</span>, <span class="keyword">false</span>);</span><br><span class="line">                map.put(<span class="string">"errorInfo"</span>, <span class="string">"该用户已封禁，请联系管理员！"</span>);</span><br><span class="line">                subject.logout();</span><br><span class="line">            &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                currentUser.setLatelyLoginTime(<span class="keyword">new</span> Date());</span><br><span class="line">                userService.save(currentUser);</span><br><span class="line">                <span class="comment">//未读消息数放到session</span></span><br><span class="line">                Integer messageCount = messageService.getCountByUserId(currentUser.getUserId());</span><br><span class="line">                currentUser.setMessageCount(messageCount);</span><br><span class="line">                <span class="comment">//失效资源数</span></span><br><span class="line">                Article s_article = <span class="keyword">new</span> Article();</span><br><span class="line">                s_article.setUseful(<span class="keyword">false</span>);</span><br><span class="line">                s_article.setUser(currentUser);</span><br><span class="line">                session.setAttribute(Consts.UN_USEFUL_ARTICLE_COUNT,articleService.getCount(s_article,<span class="keyword">null</span>,<span class="keyword">null</span>,<span class="keyword">null</span>));</span><br><span class="line">                session.setAttribute(Consts.CURRENT_USER,currentUser);</span><br><span class="line">                map.put(<span class="string">"success"</span>, <span class="keyword">true</span>);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;<span class="keyword">catch</span> (Exception e)&#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">            map.put(<span class="string">"success"</span>, <span class="keyword">false</span>);</span><br><span class="line">            map.put(<span class="string">"errorInfo"</span>, <span class="string">"用户名或密码错误！"</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> map;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><strong>3.1.3 找回密码</strong><br>&ensp;&ensp;&ensp;&ensp;用户可通过邮箱进行密码找回。<br>&ensp;&ensp;&ensp;&ensp;首先要用SpringBoot实现一个给用户发送邮件的功能：<br>&ensp;&ensp;&ensp;&ensp;1 在QQ邮箱中将POP3/SMTP开启，并点击生成授权码，根据QQ邮箱系统的提示发送短信，</p>
<div align=center>

<p><img src="https://img-blog.csdnimg.cn/20200605111012339.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQ1NzcwNTMy,size_16,color_FFFFFF,t_70" alt="在这里插入图片描述"></div></p>
<p>&ensp;&ensp;&ensp;&ensp;2 定义关于邮箱发送邮件的配置类（这是一个真正用法发送邮件的方法）</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"> <span class="comment">//邮件配置类</span></span><br><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MailConfig</span> </span>&#123;</span><br><span class="line">    <span class="comment">//获取邮件发送实例</span></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> MailSender <span class="title">mailSender</span><span class="params">()</span></span>&#123;</span><br><span class="line">        JavaMailSenderImpl mailSender = <span class="keyword">new</span> JavaMailSenderImpl();</span><br><span class="line">        mailSender.setHost(<span class="string">"smtp.qq.com"</span>);          <span class="comment">//指定用来发送Email的邮件服务器主机名</span></span><br><span class="line">        mailSender.setPort(<span class="number">587</span>);                    <span class="comment">//默认端口，标准的SMTP端口</span></span><br><span class="line">        mailSender.setUsername(<span class="string">"用户名"</span>);   <span class="comment">//用户名</span></span><br><span class="line">        mailSender.setPassword(<span class="string">"密码是收到的短信中的密码"</span>);                 <span class="comment">//密码</span></span><br><span class="line">        <span class="keyword">return</span>  mailSender;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>&ensp;&ensp;&ensp;&ensp;3 编写生成验证码并发送邮件的controller方法<br>&ensp;&ensp;&ensp;&ensp;注意为了让方法生效，页面也可以看得到，需要在shrio配置类的第一个方法中的过滤器链中加入这些页面及其对应的方法。验证码发送以后要保存在session中，后面验证验证码填写是否正确的时候会用得到。userId也应该存储进session，后面验证验证码的时候同样用的到。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 发送验证码，传进来的参数是用户的邮箱地址</span></span><br><span class="line"><span class="meta">@ResponseBody</span></span><br><span class="line"><span class="meta">@PostMapping</span>(<span class="string">"/sendEmail"</span>)</span><br><span class="line"><span class="function"><span class="keyword">public</span> Map&lt;String,Object&gt; <span class="title">sendEmail</span><span class="params">(String email, HttpSession session)</span></span>&#123;</span><br><span class="line">    Map&lt;String,Object&gt; map = <span class="keyword">new</span> HashMap&lt;&gt;();</span><br><span class="line">    <span class="keyword">if</span>(StringUtil.isEmpty(email))&#123;<span class="comment">//如果邮箱地址为空则报错</span></span><br><span class="line">        map.put(<span class="string">"success"</span>,<span class="keyword">false</span>);</span><br><span class="line">        map.put(<span class="string">"errorInfo"</span>,<span class="string">"邮箱不能为空！"</span>);</span><br><span class="line">        <span class="keyword">return</span> map;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">//验证邮件是否存在</span></span><br><span class="line">    User u = userService.findByEmail(email);</span><br><span class="line">    <span class="keyword">if</span>(u==<span class="keyword">null</span>)&#123;</span><br><span class="line">        map.put(<span class="string">"success"</span>,<span class="keyword">false</span>);</span><br><span class="line">        map.put(<span class="string">"errorInfo"</span>,<span class="string">"邮箱不存在！"</span>);</span><br><span class="line">        <span class="keyword">return</span> map;</span><br><span class="line">    &#125;</span><br><span class="line">    String mailCode = StringUtil.genSixRandom();<span class="comment">//自定义的一个util，随机生成验证码</span></span><br><span class="line">    <span class="comment">//发邮件</span></span><br><span class="line">    SimpleMailMessage message = <span class="keyword">new</span> SimpleMailMessage();        <span class="comment">//消息构造器，这里只是构造消息，真正的发送任务，又配置类中的方法完成</span></span><br><span class="line">    message.setFrom(<span class="string">"123456@qq.com"</span>);                        <span class="comment">//发件人</span></span><br><span class="line">    message.setTo(email);                                       <span class="comment">//收件人</span></span><br><span class="line">    message.setSubject(<span class="string">"分享网-用户找回密码"</span>);         <span class="comment">//主题</span></span><br><span class="line">    message.setText(<span class="string">"您本次的验证码是："</span> +mailCode);            <span class="comment">//正文内容</span></span><br><span class="line">    mailSender.send(message);<span class="comment">//这里的mailSender是上文的mail配置类中的方法</span></span><br><span class="line">    System.out.println(mailCode);</span><br><span class="line">    <span class="comment">//验证码存到session</span></span><br><span class="line">    session.setAttribute(Consts.MAIL_CODE_NAME,mailCode);</span><br><span class="line">    session.setAttribute(Consts.USER_ID_NAME,u.getUserId());</span><br><span class="line"></span><br><span class="line">    map.put(<span class="string">"success"</span>,<span class="keyword">true</span>);</span><br><span class="line">    <span class="keyword">return</span> map;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>&ensp;&ensp;&ensp;&ensp;4 对用户提交的验证码进行验证，并重置密码；<br>&ensp;&ensp;&ensp;&ensp;这一步对用户提交的验证码和session中存储的后台发送给用户的验证码进行比对，若比对成功，则将密码重置为123456，；具体代码如下所示，在重置密码后虽然对用户执行的是save方法，但是其实是更新操作，因为更新和保存操作的代码写进了一个service。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 邮件验证码判断</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@ResponseBody</span></span><br><span class="line"><span class="meta">@PostMapping</span>(<span class="string">"/checkYzm"</span>)</span><br><span class="line"><span class="function"><span class="keyword">public</span> Map&lt;String,Object&gt; <span class="title">checkYzm</span><span class="params">(String yzm, HttpSession session)</span></span>&#123;</span><br><span class="line">    Map&lt;String,Object&gt; map = <span class="keyword">new</span> HashMap&lt;&gt;();</span><br><span class="line">    <span class="keyword">if</span>(StringUtil.isEmpty(yzm))&#123;</span><br><span class="line">        map.put(<span class="string">"success"</span>,<span class="keyword">false</span>);</span><br><span class="line">        map.put(<span class="string">"errorInfo"</span>,<span class="string">"验证码不能为空！"</span>);</span><br><span class="line">        <span class="keyword">return</span> map;</span><br><span class="line">    &#125;</span><br><span class="line">    String mailCode = (String) session.getAttribute(Consts.MAIL_CODE_NAME);</span><br><span class="line">    Integer userId = (Integer) session.getAttribute(Consts.USER_ID_NAME);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span>(!yzm.equals(mailCode))&#123;</span><br><span class="line">        map.put(<span class="string">"success"</span>,<span class="keyword">false</span>);</span><br><span class="line">        map.put(<span class="string">"errorInfo"</span>,<span class="string">"验证码错误！"</span>);</span><br><span class="line">        <span class="keyword">return</span> map;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//给用户重置密码为123456</span></span><br><span class="line">    User user = userService.getById(userId);</span><br><span class="line">    user.setPassword((CryptographyUtil.md5(Consts.PASSWORD,CryptographyUtil.SALT)));</span><br><span class="line">    userService.save(user);</span><br><span class="line">    map.put(<span class="string">"success"</span>,<span class="keyword">true</span>);</span><br><span class="line">    <span class="keyword">return</span> map;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p> <strong>3.1.4 资源和资源类型相关功能</strong><br>&ensp;&ensp;&ensp;&ensp;前文完成了注册、登录和密码找回功能。资源经过审核以后会显示在页面上，接下来对资源和资源类型相关的功能进行实现。先完成资源和资源类型相关的Entity、Mapper和Service。Mapper相对固定且简单，这里不再赘述。service方法如下所示：<br>&ensp;&ensp;&ensp;&ensp;对于资源和资源类型一旦生成就很少进行更改和删除，对其进行的大部分操作都是查询，所以在这一部分中引入了Redis缓存，并用的SpringBoot的RedisTemplate来实现Redis的访问操作。使用过程包括：<br>&ensp;&ensp;&ensp;&ensp;1当进行保存的时候，先调用Mapper中的方法进行save，如果save前redis为null，则调用redisTemplate.opsForList().rightPush(Consts.ALL_ARC_TYPE_NAME,arcType)将数据保存进redis，否则调用redisTemplate.delete(Consts.ALL_ARC_TYPE_NAME);删除掉redis中的数据（资源类型直接按上述操作就行，但是资源必须是审核以后才放入到redis中）；<br>&ensp;&ensp;&ensp;&ensp;2 在获取资源的时候如果redis中有资源则直接从redis中取，否则去数据库中去取，取完以后将资源放入redis后返回；<br>&ensp;&ensp;&ensp;&ensp;3 删除的时候先将Redis中的数据删除掉，再删除数据库中的数据；这些顺序是不能反的，否则在高并发（虽然本项目不会出现高并发）过程中可能会出现“不安全”问题；</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"> <span class="comment">//资源类型service中的方法</span></span><br><span class="line"> <span class="comment">/**</span></span><br><span class="line"><span class="comment">    * 分页查询资源类型列表</span></span><br><span class="line"><span class="comment">    * <span class="doctag">@param</span> page          当前页</span></span><br><span class="line"><span class="comment">    * <span class="doctag">@param</span> pageSize      每页记录数</span></span><br><span class="line"><span class="comment">    * <span class="doctag">@param</span> direction     排序规则</span></span><br><span class="line"><span class="comment">    * <span class="doctag">@param</span> properties    排序字段</span></span><br><span class="line"><span class="comment">    * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">    */</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> List&lt;ArcType&gt; <span class="title">list</span><span class="params">(Integer page, Integer pageSize, Direction direction,String... properties)</span></span>;</span><br><span class="line">   <span class="comment">/**</span></span><br><span class="line"><span class="comment">    * 查询资源类型列表</span></span><br><span class="line"><span class="comment">    * <span class="doctag">@param</span> direction     排序规则</span></span><br><span class="line"><span class="comment">    * <span class="doctag">@param</span> properties    排序字段</span></span><br><span class="line"><span class="comment">    * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">    */</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> List <span class="title">listAll</span><span class="params">(Direction direction,String... propert</span></span></span><br><span class="line"><span class="function"><span class="params">  // 获取总计录数</span></span></span><br><span class="line"><span class="function"><span class="params">   <span class="keyword">public</span> Long getCount()</span></span>;</span><br><span class="line"><span class="comment">//添加或修改资源类型</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">save</span><span class="params">(ArcType arcType)</span></span>;</span><br><span class="line"><span class="comment">//根据id删除一条资源类型</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">delete</span><span class="params">(Integer id)</span></span>;</span><br><span class="line">   <span class="comment">//根据id查询一条资源类型</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> ArcType <span class="title">getById</span><span class="params">(Integer id)</span></span>;</span><br></pre></td></tr></table></figure>





<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br></pre></td><td class="code"><pre><span class="line">	<span class="comment">//资源相关的service</span></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 根据分页条件查询资源信息列表</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> s_article 条件</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> nickname  用户昵称</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> s_bpublishDate    发布开始时间</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> s_epublishDate    发布结束时间</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> page              当前页</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> pageSize          每页记录数</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> direction         排序规则</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> properties        排序字段</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> List&lt;Article&gt; <span class="title">list</span><span class="params">(Article s_article, String nickname, String s_bpublishDate, String s_epublishDate, Integer page, Integer pageSize, Direction direction, String... properties)</span></span>;</span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 根据条件获取总记录数</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> s_article 条件</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> nickname  用户昵称</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> s_bpublishDate    发布开始时间</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> s_epublishDate    发布结束时间</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Long <span class="title">getCount</span><span class="params">(Article s_article, String nickname, String s_bpublishDate, String s_epublishDate)</span></span>;</span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 增加或修改资源</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> article   资源实体</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">save</span><span class="params">(Article article)</span></span>;</span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 根据主键id删除资源</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> id    资源id</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">delete</span><span class="params">(Integer id)</span></span>;</span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 根据主键id获取资源信息</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> id   资源id</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Article <span class="title">getById</span><span class="params">(Integer id)</span></span>;</span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 根据条件分页查询资源信息（前台）</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> type      类型id</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> page      当前页</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> pageSize  每页记录数</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Map&lt;String,Object&gt; <span class="title">list</span><span class="params">(String type,Integer page,Integer pageSize)</span></span>;</span><br><span class="line">     <span class="comment">//查询所有审核通过的资源信息列表</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> List&lt;Article&gt; <span class="title">listStatePass</span><span class="params">()</span></span>;</span><br><span class="line">    <span class="comment">// 点击+1</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">updateClick</span><span class="params">(Integer articleId)</span></span>;</span><br><span class="line">    <span class="comment">// 今日发布资源总数</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Integer <span class="title">todayPublish</span><span class="params">()</span></span>;</span><br><span class="line">     <span class="comment">//未审核资源总数</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Integer <span class="title">noAudit</span><span class="params">()</span></span>;</span><br><span class="line">    <span class="comment">//10条最新资源</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> List&lt;Article&gt; <span class="title">getNewArticle</span><span class="params">(Integer n)</span></span>;</span><br><span class="line">    <span class="comment">//10条热门资源(按点击排序)</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> List&lt;Article&gt; <span class="title">getClickArticle</span><span class="params">(Integer n)</span></span>;</span><br><span class="line">    <span class="comment">//10条随机资源（热搜推荐）</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> List&lt;Article&gt; <span class="title">getRandomArticle</span><span class="params">(Integer n)</span></span>;</span><br></pre></td></tr></table></figure>
<p><strong>3.1.5资源查询</strong><br>&ensp;&ensp;&ensp;&ensp;按照条件对资源进行分页查询，其实这一部分也是用户管理的范围，这里的资源查询只是查询当前用户的资源，关于分页查询的service后面继续完善。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 根据条件分页查询资源信息列表（只显示当前登录用户的资源）</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> s_article</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> page</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> pageSize</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> session</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@ResponseBody</span></span><br><span class="line">    <span class="meta">@RequestMapping</span>(<span class="string">"/articleList"</span>)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> Map&lt;String,Object&gt; <span class="title">articleList</span><span class="params">(Article s_article,@RequestParam(value=<span class="string">"page"</span>,required = <span class="keyword">false</span>)</span> Integer page,</span></span><br><span class="line"><span class="function">                                          @<span class="title">RequestParam</span><span class="params">(value=<span class="string">"limit"</span>,required = <span class="keyword">false</span>)</span> Integer pageSize,HttpSession session)</span>&#123;</span><br><span class="line">        Map&lt;String,Object&gt; map = <span class="keyword">new</span> HashMap&lt;&gt;();</span><br><span class="line">        User currentUser = (User) session.getAttribute(Consts.CURRENT_USER);</span><br><span class="line">        s_article.setUser(currentUser);</span><br><span class="line">        map.put(<span class="string">"data"</span>,articleService.list(s_article,<span class="keyword">null</span>,<span class="keyword">null</span>,<span class="keyword">null</span>,page,pageSize, Sort.Direction.DESC,<span class="string">"publishDate"</span>));</span><br><span class="line">        map.put(<span class="string">"count"</span>,articleService.getCount(s_article,<span class="keyword">null</span>,<span class="keyword">null</span>,<span class="keyword">null</span>));     <span class="comment">//总计录数</span></span><br><span class="line">        map.put(<span class="string">"code"</span>,<span class="number">0</span>);</span><br><span class="line">        <span class="keyword">return</span> map;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
<p><strong>3.1.6 资源发布功能</strong><br>&ensp;&ensp;&ensp;&ensp;点击资源发布按钮后，首先进入的应该是一个controller，这个controller会帮我们完成页面跳转，跳转到资源发布页面，页面大图如下图所示；</p>
<div align=center>

<p><img src="https://img-blog.csdnimg.cn/20200605163940258.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQ1NzcwNTMy,size_16,color_FFFFFF,t_70" alt="资源发布页面"></p>
</div>

<p><strong>3.1.6 资源添加与修改</strong><br>&ensp;&ensp;&ensp;&ensp;这一部分也是用户功能部分，所以在进行操作时一定要进行判断，判断当前用户是否为资源所有者，同时不管前端代码是否对边界条件进行了考虑，我们后端都应该尽量将边界条件考虑周全。方法中分为两大部分article.getArticleId()==null时，说明数据库中没有这个资源，要进行资源添加工作，对article属性进行赋值，并将article加入到数据库中，如果article.getArticleId()！=null说明原来的数据库中有这个资源，那么我们需要对资源进行修改，不管是添加还是修改操作，操作时都应该将审核状态重新设置为待审核状态，管理员审核以后再进行发布。在点击资源修改按钮的时候，首先被执行的是一个判断当前用户是否是资源拥有者的controller方法，如果不是controller则会提供报错信息，如果是则会进入到一个页面跳转的controller，这个页面跳转controller会将页面跳转到资源修改页面，用户在资源修改页面对资源进行修改后点击提交，页面保存的controller被执行，更新成功；</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 进入资源发布页面</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@GetMapping</span>(<span class="string">"toAddArticle"</span>)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">toAddArticle</span><span class="params">()</span></span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="string">"user/addArticle"</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 添加或修改资源</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@ResponseBody</span></span><br><span class="line">    <span class="meta">@PostMapping</span>(<span class="string">"/saveArticle"</span>)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> Map&lt;String,Object&gt; <span class="title">saveArticle</span><span class="params">(Article article,HttpSession session)</span> <span class="keyword">throws</span> IOException </span>&#123;</span><br><span class="line">        Map&lt;String,Object&gt; resultMap = <span class="keyword">new</span> HashMap&lt;&gt;();</span><br><span class="line">        <span class="keyword">if</span>(article.getPoints()&lt;<span class="number">0</span>||article.getPoints()&gt;<span class="number">10</span>)&#123;</span><br><span class="line">            resultMap.put(<span class="string">"success"</span>,<span class="keyword">false</span>);</span><br><span class="line">            resultMap.put(<span class="string">"erroInfo"</span>,<span class="string">"积分超出正常区间！"</span>);</span><br><span class="line">            <span class="keyword">return</span> resultMap;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">if</span>(!CheckShareLinkEnableUtil.check(article.getDownload()))&#123;</span><br><span class="line">            resultMap.put(<span class="string">"success"</span>,<span class="keyword">false</span>);</span><br><span class="line">            resultMap.put(<span class="string">"erroInfo"</span>,<span class="string">"百度云分享链接已经失效，请重新发布！"</span>);</span><br><span class="line">            <span class="keyword">return</span> resultMap;</span><br><span class="line">        &#125;</span><br><span class="line">        User currentUser = (User)session.getAttribute(Consts.CURRENT_USER);</span><br><span class="line">        <span class="keyword">if</span>(article.getArticleId()==<span class="keyword">null</span>)&#123;               <span class="comment">//添加资源</span></span><br><span class="line">            article.setPublishDate(<span class="keyword">new</span> Date());</span><br><span class="line">            article.setUser(currentUser);</span><br><span class="line">            <span class="keyword">if</span>(article.getPoints()==<span class="number">0</span>)&#123;         <span class="comment">//积分为0时，设置为免费资源</span></span><br><span class="line">                article.setFree(<span class="keyword">true</span>);</span><br><span class="line">            &#125;</span><br><span class="line">            article.setState(<span class="number">1</span>);                <span class="comment">//未审核状态</span></span><br><span class="line">            article.setClick(<span class="keyword">new</span> Random().nextInt(<span class="number">150</span>)+<span class="number">50</span>);         <span class="comment">//设置点击数为50~200</span></span><br><span class="line">            articleService.save(article);</span><br><span class="line">            resultMap.put(<span class="string">"success"</span>,<span class="keyword">true</span>);</span><br><span class="line">        &#125;<span class="keyword">else</span>&#123;                              <span class="comment">//修改资源</span></span><br><span class="line">            Article oldArticle = articleService.getById(article.getArticleId());        <span class="comment">//获取实体</span></span><br><span class="line">            <span class="keyword">if</span>(oldArticle.getUser().getUserId().intValue()==currentUser.getUserId().intValue())&#123;        <span class="comment">//只能修改自己的资源</span></span><br><span class="line">                oldArticle.setName(article.getName());</span><br><span class="line">                oldArticle.setArcType(article.getArcType());</span><br><span class="line">                oldArticle.setDownload(article.getDownload());</span><br><span class="line">                oldArticle.setPassword(article.getPassword());</span><br><span class="line">                oldArticle.setKeywords(article.getKeywords());</span><br><span class="line">                oldArticle.setDescription(article.getDescription());</span><br><span class="line">                oldArticle.setContent(article.getContent());</span><br><span class="line">                <span class="keyword">if</span>(oldArticle.getState()==<span class="number">3</span>)&#123;           <span class="comment">//假如原先是未通过，用户点击修改，则重新审核，状态变成未审核</span></span><br><span class="line">                    oldArticle.setState(<span class="number">1</span>);</span><br><span class="line">                &#125;</span><br><span class="line">                articleService.save(oldArticle);</span><br><span class="line">                <span class="comment">//更新时需要把审核已经通过的新资源信息放入lucene</span></span><br><span class="line">                <span class="keyword">if</span>(oldArticle.getState().intValue()==<span class="number">2</span>)&#123;</span><br><span class="line">                    articleIndex.updateIndex(oldArticle);     <span class="comment">//更新索引</span></span><br><span class="line">                &#125;</span><br><span class="line">                resultMap.put(<span class="string">"success"</span>,<span class="keyword">true</span>);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> resultMap;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
<p><strong>3.1.7资源删除</strong><br>&ensp;&ensp;&ensp;&ensp;关于资源删除部分，只需要判断当前用户是否是资源所有者，如果不是则不能删除，如果是则需要先删除评论，再删除内容，再删除Lucene。因为这里还没定义评论表的Entity所以先不对这部分代码进行展示，后面会继续完善。</p>
<h2 id="3-2-管理员后台主页相关功能"><a href="#3-2-管理员后台主页相关功能" class="headerlink" title="3.2 管理员后台主页相关功能"></a>3.2 管理员后台主页相关功能</h2><p>&ensp;&ensp;&ensp;&ensp;在管理员后台的相关功能中就涉及到了权限问题，管理员后台所具备的功能如下图所示，每个功能对应不同页面，当然前端的代码是直接进行引入的。</p>
<p>&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;<img src="https://img-blog.csdnimg.cn/20200607085637641.png" alt="在这里插入图片描述"></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">在这里插入代码片</span><br></pre></td></tr></table></figure>

<p><strong>3.2.1 管理员登录</strong><br>&ensp;&ensp;&ensp;&ensp;管理员登录页面跟user的登录页面差不多（不要忘记在Shrio的filter中对管理员的登录页面进行配置），管理员登录成功后会进入IndexAdminController中的toAdminUserCenterPage方法，这个controller方法是一个页面跳转方法，页面跳转到admin/index页面,这个方法并不是所有人都能访问的，所以要对其进行权限管理，权限管理方法：在方法上加 @RequiresPermissions(value=”进入管理员主页”)注解，参数value值是随意写的，但是这个value要与Realm中info.addStringPermission(“进入管理员主页”)中参数的值相对应，同时要去编写Realm的授权方法，项目整体的Realm授权方法如下所示：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"> <span class="comment">//跳转到管理员主页面</span></span><br><span class="line"><span class="meta">@RequiresPermissions</span>(value=<span class="string">"进入管理员主页"</span>)</span><br><span class="line"><span class="meta">@RequestMapping</span>(<span class="string">"/toAdminUserCenterPage"</span>)</span><br><span class="line"><span class="function"><span class="keyword">public</span> String <span class="title">toAdminUserCenterPage</span><span class="params">()</span></span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="string">"admin/index"</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//Realm授权方法</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> AuthorizationInfo <span class="title">doGetAuthorizationInfo</span><span class="params">(PrincipalCollection principalCollection)</span> </span>&#123;</span><br><span class="line">       String userName = (String) SecurityUtils.getSubject().getPrincipal();</span><br><span class="line">       User user = userService.findByUserName(userName);</span><br><span class="line">       SimpleAuthorizationInfo info = <span class="keyword">new</span> SimpleAuthorizationInfo();</span><br><span class="line">       Set&lt;String&gt; roles = <span class="keyword">new</span> HashSet&lt;&gt;();</span><br><span class="line">       <span class="keyword">if</span>(<span class="string">"管理员"</span>.equals(user.getRoleName()))&#123;</span><br><span class="line">           roles.add(<span class="string">"管理员"</span>);</span><br><span class="line">           info.addStringPermission(<span class="string">"进入管理员主页"</span>);</span><br><span class="line">           info.addStringPermission(<span class="string">"根据id查询资源类型实体"</span>);</span><br><span class="line">           info.addStringPermission(<span class="string">"添加或修改资源类型信息"</span>);</span><br><span class="line">           info.addStringPermission(<span class="string">"删除资源类型信息"</span>);</span><br><span class="line">           info.addStringPermission(<span class="string">"分页查询资源信息列表"</span>);</span><br><span class="line">           info.addStringPermission(<span class="string">"删除资源"</span>);</span><br><span class="line">           info.addStringPermission(<span class="string">"修改资源"</span>);</span><br><span class="line">           info.addStringPermission(<span class="string">"审核资源"</span>);</span><br><span class="line">           info.addStringPermission(<span class="string">"生成所有资源帖子索引"</span>);</span><br><span class="line">           info.addStringPermission(<span class="string">"分页查询评论信息"</span>);</span><br><span class="line">           info.addStringPermission(<span class="string">"修改评论状态"</span>);</span><br><span class="line">           info.addStringPermission(<span class="string">"删除评论"</span>);</span><br><span class="line">           info.addStringPermission(<span class="string">"分页查询用户信息"</span>);</span><br><span class="line">           info.addStringPermission(<span class="string">"修改用户VIP状态"</span>);</span><br><span class="line">           info.addStringPermission(<span class="string">"修改用户状态"</span>);</span><br><span class="line">           info.addStringPermission(<span class="string">"重置用户密码"</span>);</span><br><span class="line">           info.addStringPermission(<span class="string">"用户vip等级修改"</span>);</span><br><span class="line">           info.addStringPermission(<span class="string">"用户积分充值"</span>);</span><br><span class="line">           info.addStringPermission(<span class="string">"分页查询友情链接"</span>);</span><br><span class="line">           info.addStringPermission(<span class="string">"根据Id查询友情链接实体"</span>);</span><br><span class="line">           info.addStringPermission(<span class="string">"添加或修改友情链接"</span>);</span><br><span class="line">           info.addStringPermission(<span class="string">"批量删除友情链接"</span>);</span><br><span class="line">           info.addStringPermission(<span class="string">"修改管理员密码"</span>);</span><br><span class="line">           info.addStringPermission(<span class="string">"安全退出"</span>);</span><br><span class="line">           info.addStringPermission(<span class="string">"修改热门资源状态"</span>);</span><br><span class="line">           info.addStringPermission(<span class="string">"修改免费资源状态"</span>);</span><br><span class="line">       &#125;</span><br><span class="line">       info.setRoles(roles);</span><br><span class="line">       <span class="keyword">return</span> info;</span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure>
<p><strong>3.2.2 资源类型管理</strong><br>&ensp;&ensp;&ensp;&ensp;管理员需要对资源类型进行管理（CRUD），对于service和Mapper与上文完全相同，在此处我们需要重新定义一个ArcTypeAdminController，这个controller中的方法只有管理员才能操作所以要对其权限进行配置，所有的ArcTypeAdminController中的方法都需要加@RequiresPermissions(value=””)注解，同时要去增加Realm的授权方法中info信息。在功能实现上资源类型管理和与下文的资源管理差不多，所以这里不再赘述，将在下文进行讨论。资源类型管理中的添加类型页面如下图所示：<br><img src="https://img-blog.csdnimg.cn/20200605210256807.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQ1NzcwNTMy,size_16,color_FFFFFF,t_70" alt="在这里插入图片描述"><strong>3.2.3 资源管理</strong><br>&ensp;&ensp;&ensp;&ensp;此处将会对管理员资源管理部分的功能进行详细讨论，关于这部分功能的Mapper和Service代码已经在上文进行过了讨论，在此处我们需要重新定义一个ArticleAdminController，这个controller中的方法只有管理员才能操作所以要对其权限进行配置，所有的ArticleAdminControllerr中的方法都需要加@RequiresPermissions(value=””)注解，同时要去增加Realm的授权方法中info信息。<br>&ensp;&ensp;&ensp;&ensp;<strong>分页查询功能</strong><br>&ensp;&ensp;&ensp;&ensp;首先讨论分页查询功能，分页查询页面如下所示：<br><img src="https://img-blog.csdnimg.cn/20200606091233150.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQ1NzcwNTMy,size_16,color_FFFFFF,t_70" alt="资源管理页面">&ensp;&ensp;&ensp;&ensp;分页查询功能controller代码如下所示，@RequestParam(value = “nickname”,required = false)中required = false表示这个“nickname”参数并不是必填参数。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 根据条件分页查询资源信息列表</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> s_article     条件</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> nickname      昵称</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> publishDates  发布时间段</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> page          当前页</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> pageSize      每页记录数</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@RequestMapping</span>(value = <span class="string">"/list"</span>)</span><br><span class="line">    <span class="meta">@RequiresPermissions</span>(value = <span class="string">"分页查询资源信息列表"</span>)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> Map&lt;String,Object&gt; <span class="title">list</span><span class="params">(Article s_article,</span></span></span><br><span class="line"><span class="function"><span class="params">                                   @RequestParam(value = <span class="string">"nickname"</span>,required = <span class="keyword">false</span>)</span> String nickname,</span></span><br><span class="line"><span class="function">                                   @<span class="title">RequestParam</span><span class="params">(value = <span class="string">"publishDates"</span>,required = <span class="keyword">false</span>)</span> String publishDates,</span></span><br><span class="line"><span class="function">                                   @<span class="title">RequestParam</span><span class="params">(value = <span class="string">"page"</span>,required = <span class="keyword">false</span>)</span> Integer page,</span></span><br><span class="line"><span class="function">                                   @<span class="title">RequestParam</span><span class="params">(value = <span class="string">"pageSize"</span>,required = <span class="keyword">false</span>)</span> Integer pageSize)</span>&#123;</span><br><span class="line">        Map&lt;String,Object&gt; resultMap = <span class="keyword">new</span> HashMap&lt;&gt;();</span><br><span class="line">        String s_bpublishDate = <span class="keyword">null</span>;       <span class="comment">//开始时间</span></span><br><span class="line">        String s_epublishDate = <span class="keyword">null</span>;       <span class="comment">//结束时间</span></span><br><span class="line">        <span class="keyword">if</span>(StringUtil.isNotEmpty(publishDates))&#123;</span><br><span class="line">            String[] str = publishDates.split(<span class="string">" - "</span>);       <span class="comment">//拆分时间段</span></span><br><span class="line">            s_bpublishDate = str[<span class="number">0</span>];</span><br><span class="line">            s_epublishDate = str[<span class="number">1</span>];</span><br><span class="line">        &#125;</span><br><span class="line">        resultMap.put(<span class="string">"data"</span>,articleService.list(s_article,nickname,s_bpublishDate,s_epublishDate,page,pageSize, Sort.Direction.DESC,<span class="string">"publishDate"</span>));</span><br><span class="line">        resultMap.put(<span class="string">"total"</span>,articleService.getCount(s_article,nickname,s_bpublishDate,s_epublishDate));</span><br><span class="line">        resultMap.put(<span class="string">"errorNo"</span>,<span class="number">0</span>);</span><br><span class="line">        <span class="keyword">return</span> resultMap;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
<p><strong>删除及批量删除功能</strong><br>&ensp;&ensp;&ensp;&ensp;删除和批量删除使用相同的controller方法即可，前端向方法传递的是一个关于id的字符串，各个字符串之间用“,”进行分割，后端接收到以后用split(“ ”)进行分割，然后遍历删除。在删除资源之前，需要把评论删除干净，再删除资源，删除资源后要删除资源索引，（关于评论和索引相关问题将在下文进行讨论）具体实现如下所示：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//批量删除资源</span></span><br><span class="line"><span class="meta">@RequestMapping</span>(value = <span class="string">"/delete"</span>)</span><br><span class="line"><span class="meta">@RequiresPermissions</span>(value = <span class="string">"删除资源"</span>)</span><br><span class="line"><span class="function"><span class="keyword">public</span> Map&lt;String,Object&gt; <span class="title">delete</span><span class="params">(@RequestParam(value = <span class="string">"articleId"</span>)</span> String ids)</span>&#123;</span><br><span class="line">    Map&lt;String,Object&gt; resultMap = <span class="keyword">new</span> HashMap&lt;&gt;();</span><br><span class="line">    String[] idsStr = ids.split(<span class="string">","</span>);</span><br><span class="line">    <span class="keyword">for</span>(<span class="keyword">int</span> i=<span class="number">0</span>;i&lt;idsStr.length;i++)&#123;</span><br><span class="line">        <span class="comment">//删除评论</span></span><br><span class="line">        commentService.deleteByArticleId(Integer.parseInt(idsStr[i]));</span><br><span class="line">        articleService.delete(Integer.parseInt(idsStr[i]));           <span class="comment">//删除帖子</span></span><br><span class="line">        articleIndex.deleteIndex(idsStr[i]);                        <span class="comment">//删除索引</span></span><br><span class="line">    &#125;</span><br><span class="line">    resultMap.put(<span class="string">"errorNo"</span>,<span class="number">0</span>);</span><br><span class="line">    <span class="keyword">return</span> resultMap;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><strong>审核资源</strong><br>&ensp;&ensp;&ensp;&ensp;管理员需要对user发布的资源进行审核，这一部分对管理员的资源审核功能进行说明，关于静态资源则直接引入，引入的过程中需要注意的是：在html中以.html结尾的页面都应该放在webapp目录下，而template中的html页面都需要在controller中进行跳转。在资源审核的时候前端会通过controller中的findById()方法获取到待审核的资源，并将资源展示在页面上，所以在写审核资源的功能钱，应该写个findById()方法。关于审核，其实就是在更改article的审核状态属性的值，当审核通过的时候除了更改数据库中的审核状态信息外，还要将数据添加到redis中，审核未通过的时候除了更改数据库中审核状态信息外，还应该增加审核未通过的原因。<br><strong>3.2.4 管理员-用户管理</strong><br>&ensp;&ensp;&ensp;&ensp;其实用户管理、评论管理、资源类型管理都是大同小异的，其中资源管理相对复杂一些，上文已经对资源管理进行了详细讨论，这里只对用户管理与资源管理相差较大的部分进行讨论。当然这一部分中也不要忘了在Realm中配置权限，并在Controller中加@RequiresPermissions注解。<br><strong>封禁用户</strong><br>&ensp;&ensp;&ensp;&ensp;用户表中有一个字段用来表示是否被封禁，我们直接操作这个状态就好。当然也要在Mapper 和 Service中定义相关方法，controller方法展示如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@ResponseBody</span></span><br><span class="line"><span class="meta">@RequestMapping</span>(value = <span class="string">"/updateUserState"</span>)</span><br><span class="line"><span class="meta">@RequiresPermissions</span>(value=<span class="string">"修改用户状态"</span>)</span><br><span class="line"><span class="function"><span class="keyword">public</span> Map&lt;String,Object&gt; <span class="title">updateUserState</span><span class="params">(Integer userId,<span class="keyword">boolean</span> isOff)</span></span>&#123;</span><br><span class="line">    User oldUser = userService.getById(userId);</span><br><span class="line">    oldUser.setOff(isOff);</span><br><span class="line">    userService.save(oldUser);</span><br><span class="line">    Map&lt;String,Object&gt; map = <span class="keyword">new</span> HashMap&lt;&gt;();</span><br><span class="line">    map.put(<span class="string">"success"</span>,<span class="keyword">true</span>);</span><br><span class="line">    <span class="keyword">return</span> map;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="3-3-主页相关功能"><a href="#3-3-主页相关功能" class="headerlink" title="3.3 主页相关功能"></a>3.3 主页相关功能</h2><p>&ensp;&ensp;&ensp;&ensp;这一部分我们对主页中的相关功能进行讨论，主页中的相关功能还是比较多的，关于controller，我们先定义一个名为IndexController的controller，controller中先定义跳转到主页页面的方法（这个方法的路径：@RequestMapping(“/“)），这个方法中也会将资源类型列表和资源列表按照分页的方式查找出来并让前端对其进行显示。<br><strong>3.3.1 首页中资源列表分页展示和资源按类型分页展示</strong><br>&ensp;&ensp;&ensp;&ensp;资源类型列表已经在页面上部显示后，页面上应该显示资源列表，在对资源列表进行显示之前，我们后端应该做一个查询，<strong>这个查询需要根据条件分页查询资源信息</strong>，所以我们要在ArticleService 和ArticleServiceImlp中添加相应代码。这个过程相对复杂，涉及到对Redis的操作（跟上文在service的save方法中对redis的操作有所不同，上文的操作是对单个增加的资源进行了redis存储，这里相当于一个批量存储过程,即所有资源的ID放进了一个Redis List，每个资源类型对应的所有资源ID放进了一个Redis List）。<br>&ensp;&ensp;&ensp;&ensp;<strong>在ServiceImpl中根据条件分页查询资源的业务流程如下：</strong><br>&ensp;&ensp;&ensp;&ensp;1、初始化redis模版 初始化返回值；<br>&ensp;&ensp;&ensp;&ensp;2、判断redis有没有资源列表；<br>&ensp;&ensp;&ensp;&ensp;3、如果redis里没有资源列表，去数据库查询；<br>&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;3.1、遍历资源列表；<br> &ensp;&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;3.2、将每一个资源放到redis（所有的资源进行redis缓存，点击首页按钮的时候资源进行展示的时候用得到）；<br> &ensp;&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;3.3、将每一个资源id推入redis的allarticleId列表；<br> &ensp;&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;3.4、遍历资源类型列表，将该资源推入相应的redis资源类型列表（按照类型对资源进行相应缓存，比如点击JavaEE资源类型按钮的时候，根据JavaEE类型去redis中进行查找）；<br>&ensp;&ensp;&ensp;&ensp;4、对资源列表进行分页并且返回当前页；<br>&ensp;&ensp;&ensp;&ensp;具体代码如下所示，注意可以展示的资源都是通过审核的资源，所以要定义并调用listStatePass() service方法，来获取通过审核的资源列表，listStatePass()方法代码相对简单，这里不做展示。这个方法会在IndexController的@RequestMapping(“/“)  public ModelAndView index()方法中被调用</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Override</span></span><br><span class="line">  <span class="function"><span class="keyword">public</span> Map&lt;String, Object&gt; <span class="title">list</span><span class="params">(String type, Integer page, Integer pageSize)</span> </span>&#123;</span><br><span class="line">      <span class="comment">//1、初始化redis模版 初始化返回值</span></span><br><span class="line">      redisTemplate.setKeySerializer(redisSerializer);</span><br><span class="line">      ValueOperations&lt;Object, Object&gt; opsForValue = redisTemplate.opsForValue();</span><br><span class="line">      ListOperations&lt;Object,Object&gt; opsForList = redisTemplate.opsForList();</span><br><span class="line"></span><br><span class="line">      Map&lt;String,Object&gt; resultMap = <span class="keyword">new</span> HashMap&lt;&gt;();</span><br><span class="line">      List&lt;Article&gt; tempList = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">      <span class="comment">//2、判断redis有没有资源列表</span></span><br><span class="line">      Boolean flag = redisTemplate.hasKey(<span class="string">"allarticleId"</span>);</span><br><span class="line">      <span class="comment">//3、如果redis里没有资源列表，去数据库查询</span></span><br><span class="line">      <span class="keyword">if</span>(!flag)&#123;</span><br><span class="line">          <span class="comment">//3.1、遍历资源列表</span></span><br><span class="line">          List&lt;Article&gt; listStatePass = listStatePass();</span><br><span class="line">          <span class="keyword">for</span>(Article a:listStatePass)&#123;</span><br><span class="line">              <span class="comment">//3.2、将每一个资源放到redis</span></span><br><span class="line">              opsForValue.set(<span class="string">"article_"</span>+a.getArticleId(),a);</span><br><span class="line">              <span class="comment">//3.3、将每一个资源id推入redis的allarticleId列表</span></span><br><span class="line">              opsForList.rightPush(<span class="string">"allarticleId"</span>,a.getArticleId());</span><br><span class="line">              <span class="comment">//3.4、遍历资源类型列表，将该资源推入相应的redis资源类型列表</span></span><br><span class="line">              List&lt;ArcType&gt; arcTypeList = arcTypeService.listAll(Sort.Direction.ASC,<span class="string">"sort"</span>);</span><br><span class="line">              <span class="keyword">for</span>(ArcType arcType:arcTypeList)&#123;</span><br><span class="line">                  <span class="keyword">if</span>(a.getArcType().getArcTypeId().intValue() == arcType.getArcTypeId().intValue())&#123;</span><br><span class="line">                      opsForList.rightPush(<span class="string">"article_type_"</span>+arcType.getArcTypeId(),a.getArticleId());</span><br><span class="line">                  &#125;</span><br><span class="line">              &#125;</span><br><span class="line">          &#125;</span><br><span class="line">      &#125;</span><br><span class="line"></span><br><span class="line">      <span class="comment">//4、分页资源列表并且返回当前页</span></span><br><span class="line">      <span class="keyword">long</span> start = (page-<span class="number">1</span>)*pageSize;</span><br><span class="line">      <span class="keyword">long</span> end = pageSize*page - <span class="number">1</span>;</span><br><span class="line">      List idList;</span><br><span class="line">      <span class="keyword">long</span> count;</span><br><span class="line">      <span class="keyword">if</span>(<span class="string">"all"</span>.equals(type))&#123;</span><br><span class="line">          idList = opsForList.range(<span class="string">"allarticleId"</span>,start,end);</span><br><span class="line">          count = opsForList.size(<span class="string">"allarticleId"</span>);</span><br><span class="line">      &#125;<span class="keyword">else</span>&#123;</span><br><span class="line">          idList = opsForList.range(<span class="string">"article_type_"</span>+type,start,end);</span><br><span class="line">          count = opsForList.size(<span class="string">"article_type_"</span>+type);</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="comment">//根据idList中的id取出id对应的对象，并且保存进tempList</span></span><br><span class="line">      <span class="keyword">for</span>(Object id:idList)&#123;</span><br><span class="line">          tempList.add((Article) opsForValue.get(<span class="string">"article_"</span>+id));</span><br><span class="line">      &#125;</span><br><span class="line">      resultMap.put(<span class="string">"data"</span>,tempList);</span><br><span class="line">      resultMap.put(<span class="string">"count"</span>,count);</span><br><span class="line">      <span class="keyword">return</span> resultMap;</span><br><span class="line">  &#125;</span><br></pre></td></tr></table></figure>
<p>&ensp;&ensp;&ensp;&ensp;当点击首页的时候展示的是所有类型的资源分页列表,controller<br>对应的是IndexController，而当点击某个类别按钮的时候，应该展示这个类别的资源分页列表。这里controller对应的是AtricleController（对于是哪个controller并没有严格要求只是按照功能对其进行了划分，以方便管理）。</p>
<p>&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;<img src="https://img-blog.csdnimg.cn/20200606151432958.png" alt="在这里插入图片描述"></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 按资源类型分页查询资源列表</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> type</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> currentPage</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@RequestMapping</span>(<span class="string">"/&#123;type&#125;/&#123;currentPage&#125;"</span>)</span><br><span class="line"><span class="function"><span class="keyword">public</span> ModelAndView <span class="title">type</span><span class="params">(@PathVariable(value = <span class="string">"type"</span>,required = <span class="keyword">false</span>)</span> String type, @<span class="title">PathVariable</span><span class="params">(value = <span class="string">"currentPage"</span>,required = <span class="keyword">false</span>)</span>Integer currentPage)</span>&#123;</span><br><span class="line">    ModelAndView mav = <span class="keyword">new</span> ModelAndView();</span><br><span class="line">    mav.setViewName(<span class="string">"index"</span>);</span><br><span class="line">    <span class="comment">//类型的html代码</span></span><br><span class="line">    List arcTypleList = arcTypeService.listAll(Sort.Direction.ASC,<span class="string">"sort"</span>);</span><br><span class="line">    mav.addObject(<span class="string">"arcTypeStr"</span>, HTMLUtil.getArcTypeStr(type,arcTypleList));</span><br><span class="line">    <span class="comment">//资源列表</span></span><br><span class="line">    Map&lt;String,Object&gt; map = articleService.list(type,currentPage, Consts.PAGE_SIZE);</span><br><span class="line">    mav.addObject(<span class="string">"articleList"</span>,map.get(<span class="string">"data"</span>));</span><br><span class="line">    <span class="comment">//分页html代码</span></span><br><span class="line">    mav.addObject(<span class="string">"pageStr"</span>,HTMLUtil.getPagation(<span class="string">"/article/"</span>+type,Integer.parseInt(String.valueOf(map.get(<span class="string">"count"</span>))),currentPage,<span class="string">"该分类还没有数据..."</span>));</span><br><span class="line">    <span class="keyword">return</span> mav;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><strong>3.3.2 主页查看资源详情</strong><br>&ensp;&ensp;&ensp;&ensp;首页中看到的资源都是资源名称和用户名称等信息，点开资源可以查看资源详情（这个资源详情中没有百度云链接和密码，只有点击下载后前端才会显示出资源的百度云链接和密码），所以我们应该在后台的ArticleController中编写Controller方法给前端返回文章详情。点开文章后文章的点击量应该进行+1操作（这个是不是可以用Redis完成呢），注意：这个方法也应该在Shrio过滤器中进行配置。（这里涉及到了Lucene相关的知识点）。</p>
<h1 id="4-其他功能"><a href="#4-其他功能" class="headerlink" title="4 其他功能"></a>4 其他功能</h1><p> <strong>4.1 用户下载</strong><br>&ensp;&ensp;&ensp;&ensp;关于用户下载，我们要首先定义好用户下载表的Entity实体，用户下载表中包含了下载时间、下载资源和下载用户；再写Mapper相关代码；再写Respority；最后编写Controller。service接口中的方法如下所示：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"> <span class="comment">//用户下载Service接口</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">UserDownloadService</span> </span>&#123;</span><br><span class="line">     <span class="comment">//查询某个用户下载某个资源的次数</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Integer <span class="title">getCountByUserIdAndArticleId</span><span class="params">(Integer userId,Integer articleId)</span></span>;</span><br><span class="line">     <span class="comment">//分页查询某个用户下载的所有资源</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Page&lt;UserDownload&gt; <span class="title">list</span><span class="params">(Integer userId, Integer page, Integer pageSize, Sort.Direction direction,String... properties)</span></span>;</span><br><span class="line">    <span class="comment">// 统计某个用户下载的资源数</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Long <span class="title">getCount</span><span class="params">(Integer userId)</span></span>;</span><br><span class="line">    <span class="comment">//添加或修改某用户的下载信息</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">save</span><span class="params">(UserDownload userDownload)</span></span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>&ensp;&ensp;&ensp;&ensp;在点击资源下载按钮的时候，后端的判断当前资源是否被当前用户下载过的controller方法会被执行，如果下载过，前端会弹出页面询问是否再次下载，并不会二次扣除积分，如果没有进行下载过，则前端会判断一下这个资源是否是免费资源（这由另外一个判断是否是免费资源的方法来完成），如果是免费资源则下载过程不扣除积分，否则前端将会调用判断积分是否足够的controller，积分不足则提示积分不足，如果积分足够则提示积分数目，并询问是否确定下载资源，点击确认资源下载的controller方法toDownloadPage（）会被执行，这个toDownloadPage（）方法进行了一系列操作，最后会跳转到article/downloadPage下载页面，这个下载页面会展示百度云资源和密码。如果是会员则可以点击会员免积分下载，前端会调用后端的controller中的判断用户是否是vip的方法，如果是vip则直接跳转到controller toVipDownloadPage（）方法。<br>&ensp;&ensp;&ensp;&ensp;虽然前端已经对是否下载过，积分是否足够等问题进行了判断，但是我们后端应该再进行一次判断，代码如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 跳转到资源下载页面</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@RequestMapping</span>(<span class="string">"/toDownloadPage/&#123;articleId&#125;"</span>)</span><br><span class="line"><span class="function"><span class="keyword">public</span> ModelAndView <span class="title">toDownloadPage</span><span class="params">(@PathVariable(<span class="string">"articleId"</span>)</span>Integer articleId,HttpSession session)</span>&#123;</span><br><span class="line">    Article article = articleService.getById(articleId);</span><br><span class="line">    <span class="comment">//查不到或者没审核通过，直接返回</span></span><br><span class="line">    <span class="keyword">if</span>(article==<span class="keyword">null</span>||article.getState().intValue()!=<span class="number">2</span>)&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    User currentUser = (User)session.getAttribute(Consts.CURRENT_USER);</span><br><span class="line">    <span class="comment">//判断当前用户是否下载过</span></span><br><span class="line">    <span class="keyword">int</span> count = userDownloadService.getCountByUserIdAndArticleId(currentUser.getUserId(),articleId);</span><br><span class="line">    <span class="keyword">if</span>(count==<span class="number">0</span>)&#123;           <span class="comment">//没下载过</span></span><br><span class="line">        <span class="keyword">if</span>(!article.isFree())&#123;      <span class="comment">//非免费资源</span></span><br><span class="line">            <span class="keyword">if</span>(currentUser.getPoints()-article.getPoints()&lt;<span class="number">0</span>)&#123;      <span class="comment">//积分不够</span></span><br><span class="line">                <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="comment">//扣除积分后保存到数据库</span></span><br><span class="line">            currentUser.setPoints(currentUser.getPoints()-article.getPoints());</span><br><span class="line">            userService.save(currentUser);</span><br><span class="line">            <span class="comment">//资源分享人加积分</span></span><br><span class="line">            User articleUser=article.getUser();</span><br><span class="line">            article.setPoints(articleUser.getPoints()+article.getPoints());</span><br><span class="line">            userService.save(articleUser);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">//保存用户下载</span></span><br><span class="line">        UserDownload userDownload = <span class="keyword">new</span> UserDownload();</span><br><span class="line">        userDownload.setArticle(article);</span><br><span class="line">        userDownload.setUser(currentUser);</span><br><span class="line">        userDownload.setDownloadDate(<span class="keyword">new</span> Date());</span><br><span class="line">        userDownloadService.save(userDownload);</span><br><span class="line">    &#125;</span><br><span class="line">    ModelAndView mav = <span class="keyword">new</span> ModelAndView();</span><br><span class="line">    mav.addObject(<span class="string">"article"</span>,article);</span><br><span class="line">    mav.setViewName(<span class="string">"article/downloadPage"</span>);</span><br><span class="line">    <span class="keyword">return</span> mav;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><strong>4.2 用户评论功能</strong><br>&ensp;&ensp;&ensp;&ensp;如果用户下载过某个资源，则这个用户可以对资源进行评论，后台管理员对评论进行审核，审核通过则进行展示。先定义关于评论表的Entity，这里包含了评价时间、评价内容、评价者、评价状态和所属资源相关信息。（在上文资源删除已经提到过，在删除资源的过程中后台应该先删除资源对应的评价）<br><strong>4.3评价审核</strong><br>&ensp;&ensp;&ensp;&ensp;评价审核与资源审核功能类似，这里不再赘述。<br><strong>4.4 增加评论和查询评论</strong><br>&ensp;&ensp;&ensp;&ensp;评论相关的功能比资源相关内容相似，且简单很多。<br><strong>4.5 管理员数据统计</strong><br>&ensp;&ensp;&ensp;&ensp;在管理员后台中管理员会对用户数、资源数、今日注册数、今日登录数进行统计，以方便管理员对网站进行管理。如下图所示，这其实就是对Sql聚合函数的熟练掌握学习，所以这里不再赘述。<br><img src="https://img-blog.csdnimg.cn/2020060709182763.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQ1NzcwNTMy,size_16,color_FFFFFF,t_70" alt="在这里插入图片描述"></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Autowired</span></span><br><span class="line">  <span class="keyword">private</span> CommentService commentService;</span><br><span class="line">  <span class="comment">//前端提交保存评论信息</span></span><br><span class="line">  <span class="meta">@PostMapping</span>(<span class="string">"/add"</span>)</span><br><span class="line">  <span class="function"><span class="keyword">public</span> Map&lt;String,Object&gt; <span class="title">add</span><span class="params">(Comment comment, HttpSession session)</span></span>&#123;</span><br><span class="line">      Map&lt;String,Object&gt; map = <span class="keyword">new</span> HashMap&lt;&gt;();</span><br><span class="line">      comment.setContent(StringUtil.esc(comment.getContent()));</span><br><span class="line">      comment.setCommentDate(<span class="keyword">new</span> Date());</span><br><span class="line">      comment.setState(<span class="number">0</span>);</span><br><span class="line">      comment.setUser((User)session.getAttribute(Consts.CURRENT_USER));</span><br><span class="line">      commentService.save(comment);</span><br><span class="line">      map.put(<span class="string">"success"</span>,<span class="keyword">true</span>);</span><br><span class="line">      <span class="keyword">return</span> map;</span><br><span class="line">  &#125;</span><br><span class="line">   <span class="comment">//分页查询某个资源的评论信息</span></span><br><span class="line">  <span class="meta">@ResponseBody</span></span><br><span class="line">  <span class="meta">@RequestMapping</span>(value = <span class="string">"/list"</span>)</span><br><span class="line">  <span class="function"><span class="keyword">public</span> Map&lt;String,Object&gt; <span class="title">list</span><span class="params">(Comment s_comment, @RequestParam(value = <span class="string">"page"</span>,required = <span class="keyword">false</span>)</span>Integer page)</span>&#123;</span><br><span class="line">      s_comment.setState(<span class="number">1</span>);</span><br><span class="line">      Page&lt;Comment&gt; commentPage = commentService.list(s_comment,page,<span class="number">5</span>, Sort.Direction.DESC,<span class="string">"commentDate"</span>);</span><br><span class="line">      Map&lt;String,Object&gt; map = <span class="keyword">new</span> HashMap&lt;&gt;();</span><br><span class="line">      map.put(<span class="string">"data"</span>, HTMLUtil.getCommentPageStr(commentPage.getContent()));          <span class="comment">//评论的HTML代码</span></span><br><span class="line">      map.put(<span class="string">"total"</span>,commentPage.getTotalPages());                                   <span class="comment">//总页数</span></span><br><span class="line">      <span class="keyword">return</span> map;</span><br><span class="line">  &#125;</span><br></pre></td></tr></table></figure>


<h1 id="5-相关知识点"><a href="#5-相关知识点" class="headerlink" title="5 相关知识点"></a>5 相关知识点</h1><h2 id="5-1-Redis"><a href="#5-1-Redis" class="headerlink" title="5.1 Redis"></a>5.1 Redis</h2><p>redis用到了String和List数据结构 3.3节中有详细说明</p>
<h2 id="5-2-按条件分页查询"><a href="#5-2-按条件分页查询" class="headerlink" title="5.2 按条件分页查询"></a>5.2 按条件分页查询</h2><p>&ensp;&ensp;&ensp;&ensp;可以采用MySql的Limit分页查询，客户端通过传递start(页码)，pageSize(每页显示的条数)两个参数去分页查询数据库表中的数据，那我们知道MySql数据库提供了分页的函数limit m,n，但是该函数的用法和我们的需求不一样，所以就需要我们根据实际情况去改写适合我们自己的分页语句，通过分析，可以得出符合我们需求的分页sql格式是：select * from table limit (start-1)*pageSize,pageSize; 其中start是页码，pageSize是每页显示的条数。当需要进行按条件分页查询的时候需要在Sql中加入查询条件，如select * from orders_history where type=2<br>and id between 1000000 and 1000100 limit 100; 当然也可以采用PageHelper进行分页查询。</p>
<h2 id="5-3-MySql"><a href="#5-3-MySql" class="headerlink" title="5.3 MySql"></a>5.3 MySql</h2><p>&ensp;&ensp;&ensp;&ensp;涉及多表查询:多表查询主要关注ResultMap方法。<br>&ensp;&ensp;&ensp;&ensp;聚合函数（管理员后台统计用户数、资源数、当日登陆人数等信息的时候用得到）</p>
<h2 id="5-4-SpringBoot"><a href="#5-4-SpringBoot" class="headerlink" title="5.4 SpringBoot"></a>5.4 SpringBoot</h2><p>&ensp;&ensp;&ensp;&ensp;直接推荐尚硅谷在B站发布的视频吧，讲的太好了<br>&ensp;&ensp;&ensp;&ensp;<strong>事务管理</strong>：在掌握SpringBoot的事务管理之前，先学习一下Spring的事务管理，<a href="https://blog.csdn.net/donggua3694857/article/details/69858827" target="_blank" rel="noopener">参考博文链接</a>。<br>以前学ssh ssm都有事务管理service层，通过applicationContext.xml配置，在service类或所有service方法都加上事务操作；用来保证一致性，即service方法里的多个dao操作，要么同时成功，要么同时失败；springboot下的话 搞一个@Transactional即可，无需再进行配置。SpringBoot项目会自动配置一个 DataSourceTransactionManager，所以我们只需在方法（或者类）加上 @Transactional 注解（一般是Service方法上），就自动纳入 Spring 的事务管理了<br><a href="https://blog.csdn.net/eeeeasy/article/details/80834992" target="_blank" rel="noopener">参考文献1</a><br><strong>事务管理的注意事项</strong>：<br>&ensp;&ensp;&ensp;&ensp;1.不要在接口上声明@Transactional ，而要在具体类的方法上使用 @Transactional 注解，否则注解可能无效。<br>&ensp;&ensp;&ensp;&ensp;2.不要图省事，将@Transactional放置在类级的声明中，放在类声明，会使得所有方法都有事务。故@Transactional应该放在方法级别，不需要使用事务的方法，就不要放置事务，比如查询方法。否则对性能是有影响的。<br>&ensp;&ensp;&ensp;&ensp;3.使用了@Transactional的方法，对同一个类里面的方法调用， @Transactional无效。比如有一个类Test，它的一个方法A，A再调用Test本类的方法B（不管B是否public还是private），但A没有声明注解事务，而B有。则外部调用A之后，B的事务是不会起作用的。（经常在这里出错）<br>&ensp;&ensp;&ensp;&ensp;4.使用了@Transactional的方法，只能是public，@Transactional注解的方法都是被外部其他类调用才有效，故只能是public。道理和上面的有关联。故在 protected、private 或者 package-visible 的方法上使用 @Transactional 注解，它也不会报错，但事务无效。<br>&ensp;&ensp;&ensp;&ensp;5.spring的事务在抛异常的时候会回滚，如果是catch捕获了，事务无效。可以在catch里面加上throw new RuntimeException();<br>&ensp;&ensp;&ensp;&ensp;6.最后有个关键的一点：和锁同时使用需要注意：由于Spring事务是通过AOP实现的，所以在方法执行之前会有开启事务，之后会有提交事务逻辑。而synchronized代码块执行是在事务之内执行的，可以推断在synchronized代码块执行完时，事务还未提交，其他线程进入synchronized代码块后，读取的数据不是最新的。<br><a href="https://blog.csdn.net/Abysscarry/article/details/80189232?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.nonecase&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.nonecase" target="_blank" rel="noopener">参考文献2</a></p>
<h2 id="5-5-MyBatis"><a href="#5-5-MyBatis" class="headerlink" title="5.5 MyBatis"></a>5.5 MyBatis</h2><p>&ensp;&ensp;&ensp;&ensp;因为项目中持久层并没有使用SpringData-JPA，而是采用的MyBatis，所有要对SpringBoot和MyBatis，MyBatis的使用可以分为注解方式和Mapper配置文件方式。这里采用的是Mapper配置文件的方式，首先在POM.xml中导入依赖，在Reasource文件夹下简历MyBatis/Mapper文件夹，用来存放mapper主配置文件和映射配置文件，当然要在Application.yml中指出mapper主配置文件和映射文件的存放位置，在SpringBoot中集成MyBatis，可以在mapper接口上添加@Mapper注解，将mapper注入到Spring,但是如果每一给mapper都添加@mapper注解会很麻烦，这时可以使用@MapperScan注解来扫描包，这个MapperScan（“ ”）是加载启动类上面的。<br><strong>5.5.1 多表查询</strong><br>&ensp;&ensp;&ensp;&ensp;MyBatis的多表查询是这个项目中重点问题：比如一对多（一个用户有多个自己的资源）、多对一（多个资源属于一个用户，当针对某一特定的资源的时候只能是一对一即一个资源有一个用户，在MyBatis中对多对一是按照一对一进行处理的）、一对一（一个资源属于一个类型）；<br><strong>一对一：</strong><br>&ensp;&ensp;&ensp;&ensp; 在实现一对一的时候比如查询资源并且查出资源所对应的用户的时候，可以采用一种最粗暴的方式—建立一个新的实体类，这个实体类包含了资源和用户属性，比如建立一个ArticleUser，那么Mapper.xml中的returnType也应该改成ArticleUser，这样就把联表查询的任务交给了SQL语句，查询的结果会自动封装进ArticleUser（虽然这是一种解决方案，但是这种方法并不推荐使用）。可采用在配置文件中定义ResultMap+association的方法。<br><strong>一对多：</strong><br>&ensp;&ensp;&ensp;&ensp; 一对多关系映射中，主表实体应该包含从表实体的集合引用，即在User实体类中加上    List&lt;Article”&gt; list;并加之get和set方法。这里就涉及到了左外连接的知识点：</p>
<h2 id="5-6-Shrio"><a href="#5-6-Shrio" class="headerlink" title="5.6 Shrio"></a>5.6 Shrio</h2><p>&ensp;&ensp;&ensp;&ensp; shiroConfig 也不复杂，基本就三个方法。再说这三个方法之前，我想给大家说一下shiro的三个核心概念：<br> &ensp;&ensp;&ensp;&ensp;  Subject： 代表当前正在执行操作的用户，但Subject代表的可以是人，也可以是任何第三方系统帐号。当然每个subject实例都会被绑定到SercurityManger上。向外提供的API的核心。<br> &ensp;&ensp;&ensp;&ensp;    SecurityManger:SecurityManager是Shiro核心，主要协调Shiro内部的各种安全组件，这个我们不需要太关注，只需要知道可以设置自定的Realm。SpringMVC中DisparctherServlet的角色。<br>    Realm:用户数据和Shiro数据交互的桥梁。比如需要用户身份认证、权限认证。都是需要通过Realm来读取数据。<br> &ensp;&ensp;&ensp;&ensp;    <a href="https://blog.csdn.net/bicheng4769/article/details/86668209?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-2.nonecase&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-2.nonecase" target="_blank" rel="noopener">参考文献</a></p>

    </div>

    
    
    

      <footer class="post-footer">

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2020/06/21/weifuwu/" rel="prev" title="单机、集群、分布式和微服务等相关概念解析以及Redis实现分布式锁">
      <i class="fa fa-chevron-left"></i> 单机、集群、分布式和微服务等相关概念解析以及Redis实现分布式锁
    </a></div>
      <div class="post-nav-item">
    <a href="/2020/06/29/article/" rel="next" title="JVM参数、GC垃圾收集器、引用类型、OOM相关问题">
      JVM参数、GC垃圾收集器、引用类型、OOM相关问题 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-项目概述"><span class="nav-number">1.</span> <span class="nav-text">1 项目概述</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-数据库建立"><span class="nav-number">2.</span> <span class="nav-text">2 数据库建立</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-后端核心功能及代码实现"><span class="nav-number">3.</span> <span class="nav-text">3 后端核心功能及代码实现</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-2-管理员后台主页相关功能"><span class="nav-number">4.</span> <span class="nav-text">3.2 管理员后台主页相关功能</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-3-主页相关功能"><span class="nav-number">5.</span> <span class="nav-text">3.3 主页相关功能</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#4-其他功能"><span class="nav-number"></span> <span class="nav-text">4 其他功能</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#5-相关知识点"><span class="nav-number"></span> <span class="nav-text">5 相关知识点</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#5-1-Redis"><span class="nav-number">1.</span> <span class="nav-text">5.1 Redis</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#5-2-按条件分页查询"><span class="nav-number">2.</span> <span class="nav-text">5.2 按条件分页查询</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#5-3-MySql"><span class="nav-number">3.</span> <span class="nav-text">5.3 MySql</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#5-4-SpringBoot"><span class="nav-number">4.</span> <span class="nav-text">5.4 SpringBoot</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#5-5-MyBatis"><span class="nav-number">5.</span> <span class="nav-text">5.5 MyBatis</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#5-6-Shrio"><span class="nav-number">6.</span> <span class="nav-text">5.6 Shrio</span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">丛同学</p>
  <div class="site-description" itemprop="description">热爱可抵岁月满长</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">6</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
        <span class="site-state-item-count">6</span>
        <span class="site-state-item-name">分类</span>
      </div>
  </nav>
</div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">丛同学</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://pisces.theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Pisces</a> 强力驱动
  </div>

        








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>




  















  

  

</body>
</html>
